# backend/routers/library_router.py
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session

from backend.crud import library_crud
from backend.database import get_db
from backend.dependencies import get_current_active_user
from backend.models import User, LibraryMember
from backend.schemas import Library, LibraryCreate

router = APIRouter()


@router.post("/libraries", response_model=Library)
def create_library(
        library: LibraryCreate,
        db: Session = Depends(get_db),
        current_user: User = Depends(get_current_active_user)
):
    return library_crud.create_library(db, library.name, current_user.id)


@router.post("/libraries/join")
def join_library(
        invite_code: str,
        db: Session = Depends(get_db),
        current_user: User = Depends(get_current_active_user)
):
    library = library_crud.get_library_by_invite_code(db, invite_code)
    if not library:
        raise HTTPException(status_code=404, detail="无效的邀请码")

    # 检查用户是否已加入书阁
    existing = db.query(LibraryMember).filter(
        LibraryMember.library_id == library.id,
        LibraryMember.user_id == current_user.id
    ).first()

    if existing:
        raise HTTPException(status_code=400, detail="已加入该书阁")

    return library_crud.add_member(db, library.id, current_user.id)
